﻿using System;
using System.Configuration;
using mojoPortal.Net;
using mojoPortal.Web;
using Resources;
using mojoPortal.Web.Framework;
using System.Collections;
using mojoPortal.Business;
using ud_gSDMS.Code_Service;
using mojoPortal.Business.WebHelpers;
using System.Linq;
using System.Data;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
using ud_Utilities;
using Brettle.Web.NeatUpload;

namespace ud_gSDMS.Testing
{
    public partial class Add_Error : mojoBasePage
    {
        private int pageID = -1;
        private int id = -1;
        protected String cacheDependencyKey;
        private SiteUser _siteUser;
        private int moduleId = -1;


        void Page_Load(object sender, EventArgs e)
        {
            //try
            //{
                _siteUser = SiteUtils.GetCurrentSiteUser();

                //SiteUser.ConfirmRegistration()
                if (_siteUser == null)
                {
                    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                }
                else
                {
                    if (gSDMS_BL.mp_User_IsRole(_siteUser.UserId, "3|1") == false)
                    {
                        WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                    }
                }

                //if (!UserCanEditPage() || !UserCanViewPage())
                //{
                //    WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
                //}
                if (!Page.IsPostBack)
                {
                    PopulateLabels();
                    PopulateControls();
                }

                
            //}
            //catch
            //{
            //}
        }
        private void PopulateLabels()
        {

        }
        private void PopulateControls()
        {
            LoadSetting();
            LoadControl();

        }


        #region event
 

        void btnSend_Click(object sender, EventArgs e)
        {

            // File_Attach_ID == 0

            int errorId = 0;
            gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_ERROR_insert(id, lbError_Code.Text, txtTitle.Text, edContent.Text, 0, int.Parse(cboSender.SelectedValue), datCreate_Date.SelectedDate.Value, int.Parse(cboAssign_To.SelectedValue), int.Parse(cboStatus.SelectedValue), ref errorId);
            hidId.Value = errorId != 0 ?  errorId.ToString() : "";
            int fileID = UploadFile();
            gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_ERROR_upd(int.Parse(hidId.Value), fileID);

            if (chkSendEmail.Checked == true)
            {
                var assigned = gSDMS_BL.mp_User_get(cboAssign_To.SelectedValue, null);
                var userManager = gSDMS_BL.mp_User_get(cboSender.SelectedValue, null);
                var cc = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Get(id);

                var emailFrom = userManager.Email;
                var emailCc = cc.ud_gSDMS_PROJECT.mp_User.Email;
                var emailTo = assigned.Email;

                var subject = string.Format("[gSDMS-TESTING] PLEASE ACCEPT A NEW ERROR IN PROJECT: {0} FROM gSDMS", lbProject_Code.Text);
                var textBody = "Dear " + assigned.LoginName + "<br/><br/> You have a new error in project: <b>" + lbProject_Code.Text + "</b>. <br/><br/> <b><u>Error Code</b></u> : " + lbError_Code.Text + "<br/><br/> <b><u>Title</b></u> : " + txtTitle.Text +
                    "<br/><br/> Please enter follow link to check :" + SiteRoot + "/gsdmsmodule/Testing/TManage.aspx " + " <br/><br/> Discription : " + edContent.Text + "<br/><br/> Regard,<br/> " + userManager.LoginName;
                var siteGuid = siteSettings.SiteGuid;
                Library.SendMail(emailFrom, emailTo, emailCc, string.Empty, subject, textBody, siteGuid);
                chkSendEmail.Checked = false;
            }
                

            WebUtils.SetupRedirect(this, SiteRoot + "/gsdmsmodule/testing/Error_Lists.aspx?pageid=9&testid=" + id);
        }

        int UploadFile()
        {
            var upLoadPath = Page.Server.MapPath(WebUtils.GetApplicationRoot() + "/Data/gSDMSAttachments/");
            int fileID = 0;
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            if (hidId.Value == "")
            {
                return 0;
            }
            //if (article == null) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            //if ((article.ItemId <= 0) || (article.ModuleId != moduleId)) { WebUtils.SetupRedirect(this, Request.RawUrl); return; }
            if (file1.HasFile && file1.FileName != null && file1.FileName.Trim().Length > 0)
            {
                var repository = new ud_gSDMS_Attachments();

                string serverFileName = Guid.NewGuid() + ".config";

                var suss = repository.Create(file1.FileName, serverFileName, (int)(file1.ContentLength / 1024), out fileID, OptionForm.Testing.ToString(), hidId.Value);
                if (suss)
                {
                    var destPath = upLoadPath + serverFileName;

                    if (File.Exists(destPath))
                    {
                        File.Delete(destPath);
                        
                    }
                    
                    file1.MoveTo(destPath, MoveToOptions.Overwrite);
                }
                //BindAttachments();


                CacheHelper.TouchCacheDependencyFile(cacheDependencyKey);
            }

            return fileID;
        }

        void btnUpload_Click(object sender, EventArgs e)
        {
            
        }
        //void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        //{
        //    //if (hidId.Value != "")
        //    //    DeleteImageFromServer();
        //}
        //private void BindAttachments()
        //{
        //    var repository = new ud_gSDMS_Attachments();
        //    rptAttachments.DataSource = repository.GetByItemID(OptionForm.Testing.ToString(), hidId.Value);
        //    rptAttachments.DataBind();

        //    lblAttachments.Visible = rptAttachments.Items.Count > 0;
        //}
        
        void rptAttachments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName != "DeleteItem") return;
            var repository = new ud_gSDMS_Attachments();
            bool a = repository.DeleteItemAttachment(e.CommandArgument.ToString());
            bool b = repository.Delete(e.CommandArgument.ToString());
            if (a && b)
            {
                var path = Request.PhysicalApplicationPath + "Data/gSDMSAttachments/" + e.CommandArgument;
                path = path.Replace("/", "\\");
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "p.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            var imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            var path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            var ibtnDelete = (ImageButton)e.Item.FindControl("ibtnDelete");
            ud_Utilities.Utilities.AddConfirmButton(ibtnDelete, "Do you want to delete this file?");
        }
        #endregion event

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }


        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            //rptAttachments.ItemDataBound += rptAttachments_ItemDataBound;
            //rptAttachments.ItemCommand += rptAttachments_ItemCommand;
            
            btnSend.Click += new EventHandler(btnSend_Click);
            
            SiteUtils.SetupEditor(edContent);
            SuppressPageMenu();
        }

        private void LoadControl()
        {
        
            //gen ERROR_CODE
            if (id != -1)
            {

                var temp = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Get(id);

                if (temp != null)
                {
                    string errorCode = gSDMS_BL.ud_gSDMS_CAT_PROJECT_TEST_ERROR_CODE_AutoGenCode(id.ToString(), temp.ud_gSDMS_PROJECT.Code);

                    lbProject_Code.Text = temp.ud_gSDMS_PROJECT.Code;
                    lbError_Code.Text = errorCode;

                }



                var status = gSDMS_BL.ud_gSDMS_CAT_ERROR_STATUS_Get("Open");

                cboStatus.DataValueField = "CAT_Error_Status_ID";
                cboStatus.DataTextField = "Name";
                cboStatus.DataSource = status;
                cboStatus.DataBind();

                var users = gSDMS_BL.mp_User_Lst("3");
                cboSender.DataValueField = "UserID";
                cboSender.DataTextField = "LoginName";
                cboSender.DataSource = users;
                cboSender.DataBind();
                cboSender.SelectedValue = _siteUser.UserId.ToString();

                var projectTest = gSDMS_BL.ud_gSDMS_PROJECT_TEST_Get(id);
                var assign = gSDMS_BL.getMemberList(projectTest.Project_ID.ToString());
                cboAssign_To.DataValueField = "UserID";
                cboAssign_To.DataTextField = "LoginName";
                cboAssign_To.DataSource = assign;
                cboAssign_To.DataBind();
                cboAssign_To.SelectedValue = temp.ud_gSDMS_PROJECT.Project_Leader.ToString();
                datCreate_Date.SelectedDate = DateTime.Now.Date;
            }

        }

        private void LoadSetting()
        {
            edContent.WebEditor.ToolBar = mojoPortal.Web.Editor.ToolBar.Full;
            edContent.WebEditor.Height = 200;
        }

        private void LoadParams()
        {
            pageID = WebUtils.ParseInt32FromQueryString("pageid", pageID);
            id = WebUtils.ParseInt32FromQueryString("testid", true, id);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            cacheDependencyKey = "Module-" + moduleId.ToInvariantString();
        }

        private void LoadPanels()
        {
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }
        #endregion
    }
}